// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below. SI SE MODIFICO de nuevo
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require best_in_place
//= require_tree .
//= require twitter/bootstrap
//= require twitter/bootstrap/tooltip

$(document).ready(function(){
    $('a[rel="tooltip"]').tooltip();
    $('a[rel="nofollow"]').tooltip();
    
    //jQuery(".best_in_place").best_in_place();

    $('.select').data("live-search","true").data({"size":"15","width":"100%"}).selectpicker();

    var tipoMoneda = $('#orden_compra_TipoMoneda').val();


    // Deshabilitar tecla enter
    $("input[type=text]").keypress(function(e){

        if ( e.which == 13 ) return false;
    });

    $('#menu-lateral > ul > li > a').click(function() {
        $('#menu-lateral li').removeClass('selected');
        $(this).closest('li').addClass('selected');
        var checkElement = $(this).next();
        if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
            $(this).closest('li').removeClass('selected');
            checkElement.slideUp(600);
        }
        if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
            $('#menu-lateral ul ul:visible').slideUp(600);
            checkElement.slideDown(600);
        }
        if($(this).closest('li').find('ul').children().length == 0) {
            return true;
        } else {
            return false;
        }
    });

    $(".focus").focus(function() {
        $(this).closest(".login-text").addClass("focused");
    }).blur(function() {
        $(this).closest(".login-text").removeClass("focused");
    });


    // Funcion de Click Derecho
    var contextMenu = $("#contextMenu");
    var rowClicked;

    $("body").on("contextmenu", "table tr", function(e){
        rowClicked = $(this);
        //console.log(rowClicked);
        //siblings obtiene todos los hermanos
        rowClicked.siblings().removeClass("row-select");
        rowClicked.addClass("row-select", this.rowClicked);
        contextMenu.css({
            display: "block",
            left: e.pageX,
            top: e.pageY
        });

        return false;
    });

    contextMenu.on("click", "a", function(){
        var message = "Diste click en la fila '" + rowClicked.children("*")[1].innerHTML + "'\n";
        message += "y seleccionaste el menu item '" + $(this).text() +"'";
        alert(message);
        //console.log("bien");
        contextMenu.hide();
    });

    $("body").click(function(){
        contextMenu.hide();
    });

    //Pintar renglon de la tabla items al seleccionarlo
    $("#tabla_items tbody tr").on("click", function(){
        $(this).closest("table").find("td").removeClass("row-seleccionado");
        $(this).find("td").addClass("row-seleccionado");
    });

    $('#rootwizard').bootstrapWizard({onTabShow: function(tab, navigation, index) {
        var $total = navigation.find('li').length;
        var $current = index+1;
        var $percent = ($current/$total) * 100;
        $('#footer').find('.bar').css({width:$percent+'%'});
    }});


    $('.datepicker').datepicker({
        languaje: 'es'
    });

    $.fn.datepicker.dates['es'] = {
        days: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"],
        daysShort: ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom"],
        daysMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa", "Do"],
        months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
        monthsShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"],
        today: "Hoy"
    };


    // Funciones generales
//    $( ".datepicker" ).datepicker({
//        closeText: 'Cerrar',
//        prevText: '<Ant',
//        nextText: 'Sig>',
//        currentText: 'Hoy',
//        monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
//        monthNamesShort: ['Ene','Feb','Mar','Abr', 'May','Jun','Jul','Ago','Sep', 'Oct','Nov','Dic'],
//        dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
//        dayNamesShort: ['Dom','Lun','Mar','Mié','Juv','Vie','Sáb'],
//        dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','Sá'],
//        weekHeader: 'Sm',
//        dateFormat: 'yy/dd/mm',
//        firstDay: 1,
//        isRTL: false,
//        showMonthAfterYear: false,
//        yearSuffix: ''});


   //Funciones de inicio
    $('#hfb').mouseup(function(){
        $('#hideform').hide();
    });

//    $('a.embedly').live("click", function(e){
//        e.preventDefault();
//        $(this).parents('li').find('.embed').toggle();
//    });
    
    //Para la busqueda
    
    $('.search').keyup(function()
    {
            searchTable($(this).val());
    });
    
    
    $('#tblData tr.datosProveedores').dblclick(function(e) {
       //alert(e.target.getHeaders());
       var tds = $(this).find('td');
       tds.each(function(index,td){
         $("#receiving_ticket_rt_proveedor_attributes_IdProveedor").val($(td).text());  
         return false;
       });
       //
       $('#myModalProveedores').modal('hide');
    });
    
    $('#tblData tr.datosTrans').dblclick(function(e) {
       //alert(e.target.getHeaders());
       var tds = $(this).find('td');
       tds.each(function(index,td){
         $("#receiving_ticket_rt_transportista_attributes_IdTransportista").val($(td).text());  
         return false;
       });
       //
       $('#myModalTransportistas').modal('hide');
    });
    
    $("#factura").click(function(e){
        alert("entro");
        console.log($("#factura").html('input:checked'));
    });

    $("#rt_detalle_etiquetado").click(function(e){
        if($("#rt_detalle_etiquetado").is(":checked")){
            tot_piezas = $("#rt_detalle_total_piezas").val();
            $("#rt_detalle_tot_etiquetas").val(tot_piezas);
            $("#rt_detalle_tot_etiquetas").attr("readonly", true);
        }else{
            $("#rt_detalle_tot_etiquetas").val("");
            $("#rt_detalle_tot_etiquetas").attr("readonly", false);
        }
    });
    
   // ---------------------------- SALIDAS ----------------------
        //Pintar renglon de la tabla al seleccionarlo
    $("#tbl_det_salida tbody tr").on("click", function(){
        
        $(this).closest("table").find("td").removeClass("row-seleccionado");
        $(this).find("td").addClass("row-seleccionado");
        det_rt_id = this.id;
        llenar_campos_det_salida(det_rt_id);
    });
    

   // ---------------------------- END SALIDAS --------------------
    

});


function searchTable(inputVal)
{
	var table = $('#tblData');
	table.find('tr').each(function(index, row)
	{
		var allCells = $(row).find('td');
		if(allCells.length > 0)
		{
			var found = false;
			allCells.each(function(index, td)
			{
				var regExp = new RegExp(inputVal, 'i');
				if(regExp.test($(td).text()))
				{
					found = true;
					return false;
				}
			});
			if(found == true)$(row).show();else $(row).hide();
		}
	});
}






$(function() {
    /*
    number of fieldsets
    */
    var fieldsetCount = $('#formElem').children().length;
 
    /*
    current position of fieldset / navigation link
    */
    var current     = 1;
 
    /*
    sum and save the widths of each one of the fieldsets
    set the final sum as the total width of the steps element
    */
    var stepsWidth  = 0;
    var widths      = new Array();
    $('#steps .step').each(function(i){
        var $step       = $(this);
        widths[i]       = stepsWidth;
        stepsWidth      += $step.width();
    });
    $('#steps').width(stepsWidth);
 
    /*
    to avoid problems in IE, focus the first input of the form
    */
    $('#formElem').children(':first').find(':input:first').focus(); 
 
    /*
    show the navigation bar
    */
    $('#navigation').show();
 
    /*
    when clicking on a navigation link
    the form slides to the corresponding fieldset
    */
    $('#navigation a').bind('click',function(e){
        var $this   = $(this);
        var prev    = current;
        $this.closest('ul').find('li').removeClass('selected');
        $this.parent().addClass('selected');
        /*
        we store the position of the link
        in the current variable
        */
       
        current = $this.parent().index() + 1;
        /*
        animate / slide to the next or to the corresponding
        fieldset. The order of the links in the navigation
        is the order of the fieldsets.
        Also, after sliding, we trigger the focus on the first
        input element of the new fieldset
        If we clicked on the last link (confirmation), then we validate
        all the fieldsets, otherwise we validate the previous one
        before the form slided
        */
        $('#steps').stop().animate({
            marginLeft: '-' + widths[current-1] + 'px'
        },500,function(){
            if(current == fieldsetCount)
                validateSteps();
            else
                validateStep(prev);
            $('#formElem').children(':nth-child('+ parseInt(current) +')').find(':input:first').focus();
        });
        e.preventDefault();
    });
 
    /*
    clicking on the tab (on the last input of each fieldset), makes the form
    slide to the next step
    */
    $('#formElem > fieldset').each(function(){
        var $fieldset = $(this);
        $fieldset.children(':last').find(':input').keydown(function(e){
            if (e.which == 9){
                $('#navigation li:nth-child(' + (parseInt(current)+1) + ') a').click();
                /* force the blur for validation */
                $(this).blur();
                e.preventDefault();
            }
        });
    });
 
    /*
    validates errors on all the fieldsets
    records if the form has errors in $('#formElem').data()
    */
    function validateSteps(){
        var FormErrors = false;
        for(var i = 1; i < fieldsetCount; ++i){
            var error = validateStep(i);
            if(error == -1)
                FormErrors = true;
        }
        $('#formElem').data('errors',FormErrors);
    }
 
    /*
    validates one fieldset
    and returns -1 if errors found, or 1 if not
    */
    function validateStep(step){
        if(step == fieldsetCount) return;
 
        var error = 1;
        var hasError = false;
        $('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){
            var $this       = $(this);
            var valueLength = jQuery.trim($this.val()).length;
 
            if(valueLength == ''){
                hasError = true;
                $this.css('background-color','#FFEDEF');
            }
            else
                $this.css('background-color','#FFFFFF');
        });
        var $link = $('#navigation li:nth-child(' + parseInt(step) + ') a');
        $link.parent().find('.error,.checked').remove();
 
        var valclass = 'checked';
        if(hasError){
            error = -1;
            valclass = 'error';
        }
        $('<span class="'+valclass+'"></span>').insertAfter($link);
 
        return error;
    }
 
    /*
    if there are errors don't allow the user to submit
    */
    $('#registerButton').bind('click',function(){
        if($('#formElem').data('errors')){
            alert('Please correct the errors in the Form');
            return false;
        }
    });
    
    
//     $("input[type=text]").focusout(function(e) {
//         //alert($(this).val());
//         var valor = $(this).val();
//         var idObjeto = $(this).attr('id');
//         var idObjetoN = idObjeto.substring(17);
//         //alert('"'+ idObjetoN + '"');
//         //$("#ConsecCliente").text(valor);
//         $('"#'+ idObjetoN + '"').text(valor);
//         
//         //
//
//      });
      
      $("#confirmar").click(function(){
          //Generales
          var vRtipo_entrada = $("#receiving_ticket_IdTipoEntrada option:selected").html(); //$("#receiving_ticket_IdTipoEntrada").val();
          var vRConsecCliente = $("#receiving_ticket_ConsecCliente").val();
          var vRDestino = $("#receiving_ticket_IdDestino option:selected").html();
          var vRFechaRec = $("#receiving_ticket_FechaRecepcion").val();  
          var vRHora = $("#receiving_ticket_Hora").val();
          
          //Proveedor
          var vRProveedor = $("#receiving_ticket_rt_proveedor_attributes_IdProveedor option:selected").html();          
          var vRFacturas = $("#receiving_ticket_rt_proveedor_attributes_Facturas").val();
          var vROrdenCompra = $("#receiving_ticket_rt_proveedor_attributes_OrdenCompra").val();
          var vRValTotEmbarque = $("#receiving_ticket_rt_proveedor_attributes_ValTotEmbarque").val();
          var vRPackingList = $("#receiving_ticket_rt_proveedor_attributes_PackingList").val();
          
          //Transportista
          var vRTransportista = $("#receiving_ticket_rt_transportista_attributes_IdTransportista option:selected").html();
          var vRBolNo = $("#receiving_ticket_rt_transportista_attributes_BolNo").val();
          var vRNoCaja = $("#receiving_ticket_rt_transportista_attributes_NoCaja").val();
          var vRNoUnidad = $("#receiving_ticket_rt_transportista_attributes_NoUnidad").val();
          var vRFormaPago = $("#receiving_ticket_rt_transportista_attributes_IdFormaPago").val();
          var vRMonto = $("#receiving_ticket_rt_transportista_attributes_Monto").val();
          
          //Mercancia
          var vRRecibio = $("#receiving_ticket_rt_mercancia_attributes_Recibio").val();
          var vRCapturado = $("#receiving_ticket_rt_mercancia_attributes_Capturado").val();
          var vRTotalPallets = $("#receiving_ticket_rt_mercancia_attributes_TotalPallets").val();
          var vRBultosPallet = $("#receiving_ticket_rt_mercancia_attributes_BultosPallet").val();
          var vRUnidadMedida = $("#receiving_ticket_rt_mercancia_attributes_UnidadMedida").val();
          var vRBultos = $("#receiving_ticket_rt_mercancia_attributes_Bultos").val();
          var vRStatus = $("#receiving_ticket_rt_mercancia_attributes_Status").val();
          var vRIncidencia = $("#receiving_ticket_rt_mercancia_attributes_Incidencia").val();
          var vRDetIncidencia = $("#receiving_ticket_rt_mercancia_attributes_DetIncidencia").val();

          $("#rtipo_entrada").text(vRtipo_entrada);
          $("#ConsecCliente").text(vRConsecCliente);
          $("#Destino").text(vRDestino);
          $("#FechaRec").text(vRFechaRec);
          $("#Hora").text(vRHora);
          
          $("#Proveedor").text(vRProveedor);
          $("#Facturas").text(vRFacturas);
          $("#OrdenCompra").text(vROrdenCompra);
          $("#ValTotEmbarque").text(vRValTotEmbarque);
          $("#PackingList").text(vRPackingList);
          
          $("#Transportista").text(vRTransportista);
          $("#BolNo").text(vRBolNo);
          $("#NoCaja").text(vRNoCaja);
          $("#NoUnidad").text(vRNoUnidad);
          $("#FormaPago").text(vRFormaPago);
          $("#Monto").text(vRMonto);
          
          $("#Recibio").text(vRRecibio);
          $("#Capturado").text(vRCapturado);
          $("#TotalPallets").text(vRTotalPallets);
          $("#BultosPallet").text(vRBultosPallet);
          $("#UnidadMedida").text(vRUnidadMedida);
          $("#Bultos").text(vRBultos);
          
          $("#Status").text(vRStatus);
          $("#Incidencia").text(vRIncidencia);
          $("#DetIncidencia").text(vRDetIncidencia);
          
      });
      
//     $("select").focusout(function(e) {
//         alert("cambio");
//      });
    
    
});


$('#myModal').modal('toggle');

// ------------ FUNCIONES ----------------
function llenar_campos_det_salida(det_rt_id){

    $.get( "/receiving_tickets/detalle/"+det_rt_id+".json", function( det_rt ) {
            $("#detalles_rt_salida_rt_detalle_id").val(det_rt_id);
            $("#detalles_rt_salida_no_parte").val(det_rt.partida);
            $("#detalles_rt_salida_descripcion").val(det_rt.descripcion);
            $("#detalles_rt_salida_cantidad").val(det_rt.cantidad);

  })
};    
